package com.itxh.mvc.adapter;

import com.itxh.annotation.ResponseBody;
import com.itxh.mvc.handler.HandlerMethod;
import com.itxh.mvc.model.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

public class RequestMappingHandlerAdapter implements HandlerAdapter {
    @Override
    public boolean supports(Object handler) {
        return (handler instanceof HandlerMethod);
    }

    @Override
    public ModelAndView handle(Object handler, HttpServletRequest request, HttpServletResponse response) throws Exception{
        HandlerMethod hm = (HandlerMethod) handler;
        Object controller = hm.getController();
        Method method = hm.getMethod();

        Object parameter = resolveParameter(method,request);

        Object returnValue = method.invoke(controller);

        handleReturnValue(returnValue,method, response);
        return null;
    }

    private void handleReturnValue(Object returnValue, Method method, HttpServletResponse response) throws Exception {
        if(method.isAnnotationPresent(ResponseBody.class)) {
            response.setContentType("text/plain");
            response.getWriter().write(returnValue.toString());
        }
    }

    private Object resolveParameter(Method method, HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            String name = parameter.getName();

        }
        return null;
    }
}
